package es.unileon.prg2.patterns.composite;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import javax.swing.JOptionPane;

import es.unileon.prg2.patterns.handler.Handler;

abstract class Composite implements Component{

	private List<Component> children = new ArrayList<Component>();
	
	@Override
	public void add(Component c) {
		this.children.add(c);
	}

	@Override
	public boolean remove(Component c) {
		boolean removed = this.children.remove(c);
		if( !removed ){
			ListIterator<Component> i = this.children.listIterator();
			while ( !removed && i.hasNext() ){
				removed = i.next().remove(c);
			}	
		}
		return removed;
	}

	@Override
	public Component search(Handler c) {
		Component found = null;
		if(c.compareTo(this.getId()) == 0){
			return this;
		}
		
		ListIterator<Component> i = this.children.listIterator();
		while ( found == null && i.hasNext() ){
			found = i.next().search(c);
		}
		
		return found;
	}
	
	@Override
	public int size() {
		int number = 0;
		for(Component c : this.children){
			number += c.size();
		}		
		return number;
	}
	
	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		
		for (Component c : this.children){
			result.append(c.toString());
			JOptionPane.showMessageDialog(null, "paso");
		}
		return result.toString();
	}
	
}
